const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const path = require('path');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// 中间件
app.use(express.json());
app.use(express.static('public'));

// 存储最新的数据
let latestData = '';

// API路由
app.get('/api/push-data', (req, res) => {
    if (latestData) {
        res.send(latestData);
        latestData = ''; // 清空数据，避免重复发送
    } else {
        res.send('');
    }
});

app.post('/api/push-data', (req, res) => {
    const data = req.body.data || req.body;
    latestData = typeof data === 'string' ? data : JSON.stringify(data);
    console.log('收到API数据:', latestData);
    
    // 广播给所有WebSocket客户端
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(latestData);
        }
    });
    
    res.json({ success: true, message: '数据已接收' });
});

// WebSocket连接处理
wss.on('connection', (ws) => {
    console.log('WebSocket客户端已连接');
    
    ws.on('message', (message) => {
        const data = message.toString();
        console.log('收到WebSocket数据:', data);
        latestData = data;
        
        // 广播给其他客户端
        wss.clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(data);
            }
        });
    });
    
    ws.on('close', () => {
        console.log('WebSocket客户端已断开');
    });
    
    ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
    });
});

// 测试页面
app.get('/', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>测试服务器</title>
            <style>
                body {
                    font-family: 'Microsoft YaHei', Arial, sans-serif;
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 20px;
                    background: #f5f5f5;
                }
                .container {
                    background: white;
                    padding: 30px;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                h1 {
                    color: #333;
                    text-align: center;
                    margin-bottom: 30px;
                }
                .section {
                    margin-bottom: 30px;
                    padding: 20px;
                    border: 1px solid #e1e1e1;
                    border-radius: 8px;
                }
                .section h3 {
                    margin-top: 0;
                    color: #555;
                }
                input, textarea, button {
                    width: 100%;
                    padding: 10px;
                    margin: 10px 0;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    font-size: 14px;
                }
                button {
                    background: #667eea;
                    color: white;
                    border: none;
                    cursor: pointer;
                    font-weight: bold;
                }
                button:hover {
                    background: #5a6fd8;
                }
                .status {
                    padding: 10px;
                    border-radius: 4px;
                    margin: 10px 0;
                    font-size: 14px;
                }
                .status.success {
                    background: #d4edda;
                    color: #155724;
                    border: 1px solid #c3e6cb;
                }
                .status.error {
                    background: #f8d7da;
                    color: #721c24;
                    border: 1px solid #f5c6cb;
                }
                .log {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                    border-radius: 4px;
                    padding: 15px;
                    max-height: 200px;
                    overflow-y: auto;
                    font-family: monospace;
                    font-size: 12px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>悬浮应用测试服务器</h1>
                
                <div class="section">
                    <h3>API接口测试</h3>
                    <input type="text" id="apiData" placeholder="输入要发送的数据" value="测试数据">
                    <button onclick="sendApiData()">发送API数据</button>
                    <div id="apiStatus"></div>
                </div>
                
                <div class="section">
                    <h3>WebSocket测试</h3>
                    <input type="text" id="wsData" placeholder="输入要发送的数据" value="WebSocket测试数据">
                    <button onclick="sendWsData()">发送WebSocket数据</button>
                    <div id="wsStatus"></div>
                </div>
                
                <div class="section">
                    <h3>连接状态</h3>
                    <div id="connectionStatus">正在连接...</div>
                </div>
                
                <div class="section">
                    <h3>接收日志</h3>
                    <div class="log" id="log"></div>
                </div>
            </div>

            <script>
                let ws = null;
                const log = document.getElementById('log');
                
                function addLog(message) {
                    const time = new Date().toLocaleTimeString();
                    log.innerHTML += \`[\${time}] \${message}\\n\`;
                    log.scrollTop = log.scrollHeight;
                }
                
                function connectWebSocket() {
                    ws = new WebSocket('ws://localhost:8081');
                    
                    ws.onopen = () => {
                        document.getElementById('connectionStatus').innerHTML = 
                            '<div class="status success">WebSocket已连接</div>';
                        addLog('WebSocket连接已建立');
                    };
                    
                    ws.onmessage = (event) => {
                        addLog('收到数据: ' + event.data);
                    };
                    
                    ws.onclose = () => {
                        document.getElementById('connectionStatus').innerHTML = 
                            '<div class="status error">WebSocket已断开</div>';
                        addLog('WebSocket连接已断开');
                        // 尝试重连
                        setTimeout(connectWebSocket, 3000);
                    };
                    
                    ws.onerror = (error) => {
                        addLog('WebSocket错误: ' + error.message);
                    };
                }
                
                async function sendApiData() {
                    const data = document.getElementById('apiData').value;
                    const status = document.getElementById('apiStatus');
                    
                    try {
                        const response = await fetch('/api/push-data', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ data })
                        });
                        
                        const result = await response.json();
                        status.innerHTML = '<div class="status success">API数据发送成功</div>';
                        addLog('API数据已发送: ' + data);
                    } catch (error) {
                        status.innerHTML = '<div class="status error">API数据发送失败: ' + error.message + '</div>';
                        addLog('API发送错误: ' + error.message);
                    }
                }
                
                function sendWsData() {
                    const data = document.getElementById('wsData').value;
                    const status = document.getElementById('wsStatus');
                    
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(data);
                        status.innerHTML = '<div class="status success">WebSocket数据发送成功</div>';
                        addLog('WebSocket数据已发送: ' + data);
                    } else {
                        status.innerHTML = '<div class="status error">WebSocket未连接</div>';
                        addLog('WebSocket未连接，无法发送数据');
                    }
                }
                
                // 页面加载时连接WebSocket
                connectWebSocket();
                addLog('测试服务器已启动');
            </script>
        </body>
        </html>
    `);
});

const PORT = 3000;
const WS_PORT = 8081;

server.listen(WS_PORT, () => {
    console.log(`测试服务器已启动`);
    console.log(`HTTP API: http://localhost:${PORT}`);
    console.log(`WebSocket: ws://localhost:${WS_PORT}`);
    console.log(`测试页面: http://localhost:${PORT}`);
    console.log(`API接口: http://localhost:${PORT}/api/push-data`);
    console.log(``);
    console.log(`使用说明:`);
    console.log(`1. 启动悬浮应用`);
    console.log(`2. 在测试页面发送数据`);
    console.log(`3. 观察悬浮应用是否自动打开百度并传递数据`);
}); 